package com.franklin.ideaplugin.easytesting.controllerclient;

import com.franklin.ideaplugin.easytesting.controllerclient.utils.ControllerUtil;
import lombok.Data;

import java.lang.reflect.Method;

/**
 * controller客户端方法
 *
 * @author Ye Junhui
 * @since 2023/6/29
 */
@Data
public class ClientMethod {

    private String methodName;

    private Class<?>[] parameterTypes;

    private Class<?> returnType;

    @Override
    public boolean equals(Object obj) {
        if (obj != null && obj instanceof ClientMethod) {
            ClientMethod other = (ClientMethod) obj;
            if ((getMethodName() == other.getMethodName())) {
                if (!returnType.equals(String.class))
                    return false;
                return equalParamTypes(parameterTypes, other.parameterTypes);
            }
        }
        return false;
    }

    boolean equalParamTypes(Class<?>[] params1, Class<?>[] params2) {
        /* Avoid unnecessary cloning */
        if (params1.length == params2.length) {
            for (int i = 0; i < params1.length; i++) {
                if (params1[i] != params2[i])
                    return false;
            }
            return true;
        }else if (params1.length == params2.length + 2){
            for (int i = 0; i < params2.length; i++) {
                if (params1[i + 3] != params2[i])
                    return false;
            }
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return getMethodName().hashCode();
    }

    /**
     * 转换
     *
     * @param method
     * @return
     */
    public static ClientMethod fromMethod(Method method) {
        ClientMethod clientMethod = new ClientMethod();
        clientMethod.setMethodName(method.getName());
        clientMethod.setParameterTypes(method.getParameterTypes());
        clientMethod.setReturnType(method.getReturnType());
        return clientMethod;
    }

    /**
     * 转换
     *
     * @param method
     * @return
     */
    public static ClientMethod fromOriginMethod(Method method) {
        ClientMethod clientMethod = fromMethod(method);
        clientMethod.setParameterTypes(ControllerUtil.getControllerMethodParameterTypes(method));
        return clientMethod;
    }
}
